<?php

namespace App\Services\Chat;


use App\Dao\ChatRoomMicrophoneDao;
use App\Event\MicrophoneNotify;
use App\Event\UserJoinExitRoomNotify;
use App\Exception\MessageException;
use App\Model\ChatRoom;
use App\Model\ChatRoomMicrophone;
use App\Model\ChatRoomUser;
use App\Model\User;
use Hyperf\Di\Annotation\Inject;
use Psr\EventDispatcher\EventDispatcherInterface;

class ChatUserService
{
    #[Inject]
    protected EventDispatcherInterface $eventDispatcher;

    #[Inject]
    protected MicroPhoneService $microPhoneService;

    /**
     * Note - 获取在聊天室的用户列表
     * DateTime 2024/9/3 18:59
     * User Admin
     * @param $room_number
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getInRoomUserList($room_number, $page = 1, $pageSize = 10)
    {
        $data = ChatRoomUser::query()->from('tb_chat_room_user AS chat_room_user')->leftJoin('tb_user AS user', 'user.id', '=', 'chat_room_user.uid')
            ->where('chat_room_user.room_number', $room_number)
            ->select(['user.nickname', 'user.head_image', 'user.sex', 'user.age', 'user.noble', 'user.wealth'])
            ->forPage($page, $pageSize)
            ->get();
        return $data->toArray();
    }

    /**
     * Note - 获取进入聊天室的用户信息
     * DateTime 2024/9/3 18:36
     * User Admin
     * @param $userId
     * @return array
     */
    public function getUserInfo($userId)
    {
        $data = User::query()->where('id', $userId)->select(['nickname', 'head_image', 'sex', 'age', 'noble', 'wealth'])->first();
        if (!$data) {
            throw new MessageException('用户不存在');
        }
        $data = modelToArray($data);
        $data['wealth'] = getWealthLevel($data['wealth']);
        return formatData(['result' => 1, 'msg' => $data]);

    }

    /**
     * Note - 用户加入房间
     * DateTime 2024/9/3 18:45
     * User Admin
     * @param $userId
     * @param $room_number
     */
    public function userJoinRoom($userId, $room_number)
    {
        $room = ChatRoom::query()->where('room_number', $room_number)->first(['valid', 'room_id']);
        if (!$room || $room['valid'] == 0) {
            throw new MessageException('房间不存在或已关闭');
        }
        if (ChatRoomUser::query()->where('uid', $userId)->where('room_number', $room_number)->exists()) {
            throw new MessageException('您已加入该房间');
        }
        ChatRoomUser::query()->insert([
            'uid' => $userId,
            'room_number' => $room_number,
            'mi_seq' => -1,
            'in_room' => 1,
            'enter_time' => time(),
            'ctime' => time()
        ]);
        $userInfo = User::query()->where('id', $userId)->select(['id', 'nickname', 'head_image', 'sex', 'age', 'noble', 'wealth'])->first();
        if ($userInfo) {
            $userInfo = modelToArray($userInfo);
            $this->eventDispatcher->dispatch(new UserJoinExitRoomNotify($userInfo, $room['room_id'], 'join_room'));
        }

    }


    /**
     * Note - 用户退出房间
     * DateTime 2024/9/11 11:58
     * User Admin
     * @param $userId
     * @param $room_number
     */
    public function userExitRoom($userId, $room_number)
    {
        $room = ChatRoom::query()->where('room_number', $room_number)->first(['valid', 'room_id']);
        if (!$room || $room['valid'] == 0) {
            throw new MessageException('房间不存在或已关闭');
        }
        if (ChatRoomUser::query()->where('uid', $userId)->where('room_number', $room_number)->exists()) {
            throw new MessageException('您已不在该房间');
        }
        ChatRoomUser::query()->where('uid', $userId)->where('room_number', $room_number)->update(['mi_seq' => -1, 'in_room' => 0]);
        $userInfo = User::query()->where('id', $userId)->select(['id', 'nickname', 'head_image', 'sex', 'age', 'noble', 'wealth'])->first();
        if ($userInfo) {
            $userInfo = modelToArray($userInfo);
            $this->eventDispatcher->dispatch(new UserJoinExitRoomNotify($userInfo, $room['room_id'], 'exit_room'));
            ChatRoomMicrophoneDao::getInstance()->downMic($room_number, $userId);
        }

    }

    /**
     * Note - 用户加入\退出麦克风
     * DateTime 2024/9/4 17:27
     * User Admin
     * @param $params
     * @return true
     */
    public function joinExitMicro($params)
    {
        $miSeq = $params['mi_seq'];
        $room_number = $params['room_number'];
        $uid = $params['uid'];
        $inviteTime = $params['invite_time'] ?? null;
        $inviteUid = $params['invite_uid'] ?? null;
        $room_id = ChatRoom::query()->where('room_number', $room_number)->value('room_id');
        if (!$room_id) {
            throw new MessageException('房间不存在或已关闭');
        }
        $exists = ChatRoomUser::query()->where('uid', $uid)->where('room_number', $room_number)->doesntExist();
        if ($exists) {
            throw new MessageException('不存在房间中');
        }
        if ($miSeq >= 0) {
            // 加入麦克风
            ChatRoomMicrophoneDao::getInstance()->upMic($room_number, $uid, $miSeq, $inviteUid, $inviteTime);
        } else {
            // 退出麦克风
            ChatRoomMicrophoneDao::getInstance()->downMic($room_number, $uid);
        }

        $microInfo = $this->microPhoneService->getMiInfo($room_number, $miSeq);
        $this->eventDispatcher->dispatch(new MicrophoneNotify($microInfo, $room_id, $uid));


    }
}